package com.pfizer.pfizerExpertForPad;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlSerializer;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.util.Xml;

import com.pfizer.DB.DataHelper;
import com.pfizer.DownLoad.DownloadProgressListener;
import com.pfizer.DownLoad.FileDownloader;
import com.pfizer.Entity.DowningFileInfo;
import com.pfizer.Entity.Handout;
import com.pfizer.Entity.Question;
import com.pfizer.Entity.Survey;
import com.pfizer.Entity.SurveyResult;
import com.pfizer.Entity.pNews;
import com.pfizer.Entity.pVideo;
import com.pfizer.Public.PublicFunc;
import com.pfizer.XmlContentHandler.SaxReadXml;

/**
 * DataSyncService--<b>系统数据同步服务<b>-- 同步影片、文章（包含文章的小測驗）、問卷調查（包含問卷調查內容）、問卷調查反饋。
 * 啟動服務進行數據同步，根據設定的各種數據的同步時間進行啟動不同的同步服務。 在同步文章、影片時候，若存在新的影片則多線程線程進行資源下載。
 * 
 * @author 樊相奎
 * @version 1.45 2011/11/19
 */
public class DataSyncService extends Service {

	// 定義主程式中事物處理程式
	private Handler handler;
	// 定義同步服務器連接字符串。
	private String NewsUrlFormat = "%s/Pens_Api/DATA_FILE/News_Board.xml";
	private String VideoUrlFormat = "%s/Pens_Api/Query.aspx?ProveCode=%s&Obj_From=%s&Obj_ID=%s&Which=Video_AllList";
	private String HandoutUrlFormat = "%s/Pens_Api/Query.aspx?ProveCode=%s&Obj_From=%s&Obj_ID=%s&Which=Handout_AllList";
	private String SurveyUrlFormat = "%s/Pens_Api/Query.aspx?ProveCode=%s&Obj_From=%s&Obj_ID=%s&Which=Survey_AllList";
	private String QuestionUrlFormat = "%s/Pens_Api/Query.aspx?ProveCode=%s&Obj_From=%s&Obj_ID=%s&Which=Questionnaire&Questionnaire_ID=%s";
	private String SurveyReplyUrlFormat = "%s/Pens_Api/Query.aspx?ProveCode=%s&Which=Questionnaire_Reply&Obj_From=%s&Obj_ID=%s";

	private File dir = null;
	private DataHelper dHelper;
	pfizerApplication pApplication;
	Context mcontext = null;
	// 定義文件下載相關變量
	private int DownCount = 0;
	private int DownedCount = 0;
	private int DownErrorCount = 0;

	private int TryCount = 0;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * onCreate：創建服務時發生
	 * 
	 * @see android.app.Service#onCreate()
	 * @see com.pfizer.pfizerExpertForPad.pfizerApplication
	 * @see com.pfizer.DB.DataHelper
	 */
	@Override
	public void onCreate() {
		super.onCreate();
		try {
			Date dt = new Date();
			mcontext = DataSyncService.this;
			InitApp initApp = new InitApp(mcontext);
			initApp.SetApp(0);
			pApplication = (pfizerApplication) mcontext.getApplicationContext();
			dHelper = pApplication.getDataHelper();
			dHelper.setLoopCount(0, dt.getTime());
			handler = new Handler() {
				@Override
				// 處理程式
				public void handleMessage(Message msg) {
					try {
						Date dt = new Date();
						switch (msg.what) {
						case 2:
							DownedCount++;
							// 單個文件下載成功
							// 判斷文件下載是否已經完成，若完成則判斷是否有下載未完成的文件存在，若存在則重新下載
							if (dHelper.getDowningCount() == 0) {
								if (DownCount == DownedCount + DownErrorCount) {
									if (DownErrorCount > 0 && TryCount < 2) {
										DownNotFinishedFileThread();
										SystemClock.sleep(1000 * 2);
									} else {
										pApplication.setDownloadFlag(false);
									}
								}
							}
							break;
						case 1:
							pApplication.setLastDownTime(dt.getTime());
							break;
						case -1:
							// 單個文件下載失敗
							DownErrorCount++;
							// 判斷文件下載是否已經完成，若完成則判斷是否有下載未完成的文件存在，若存在則重新下載
							if (dHelper.getDowningCount() == 0) {
								if (DownCount == DownedCount + DownErrorCount) {
									if (DownErrorCount > 0 && TryCount < 2) {
										DownNotFinishedFileThread();
										SystemClock.sleep(1000 * 2);
									} else {
										pApplication.setDownloadFlag(false);
									}
								}
							}
							break;
						case -2:
							DownCount--;
							// 單個文件下載失敗
							// 判斷文件下載是否已經完成，若完成則判斷是否有下載未完成的文件存在，若存在則重新下載
							if (dHelper.getDowningCount() == 0) {
								if (DownCount == DownedCount + DownErrorCount) {
									if (DownErrorCount > 0 && TryCount < 2) {
										DownNotFinishedFileThread();
										SystemClock.sleep(1000 * 2);
									} else {
										// Toast.makeText(mcontext,"数据同步完成呵呵呵呵呵呵呵",
										// 1).show();
										pApplication.setDownloadFlag(false);

									}
								}
							}
							break;
						}
					} catch (Exception ex) {
						pApplication.setDataSyncing(false);
						pApplication.setDownloadFlag(false);
					}
					super.handleMessage(msg);
				}
			};
		} catch (Exception e) {
			// TODO: handle exception
			return;
		}
	}

	/**
	 * onStart：啟動服務時發生 根據時間同步影片、文章（包含文章的小測驗）、問卷調查（包含問卷調查內容）、問卷調查反饋。
	 * 
	 * @see android.app.Service#onStart(android.content.Intent, int)
	 */
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		try {

			Date dt = new Date();
			boolean isStart = true;
			if (dt.getTime() - dHelper.getLpDateTime() < 10 * 60 * 1000) {
				if (pApplication.getDataSyncing()) {
					isStart = false;
				}
				if (dHelper.getDowningCount() > 0
						&& pApplication.getDownloadFlag()) {
					isStart = false;
				}
			}
			if (isStart) {
				SysnThread();
			}
		} catch (Exception e) {
			// TODO: handle exception
			return;
		}
	}

	/**
	 * 訊息同步線程
	 */
	private void SysnThread() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					pApplication.setDataSyncing(true);
					Date dt = new Date();
					// 初始化文件下載參數
					// 取得當前程式只是的次數
					long lcount = dHelper.getLoopCount() + 1;
					dHelper.setLoopCount(lcount, dt.getTime());
					// 設置同步過程中程式不能打開。
					TryCount = 0;
					pApplication.setLastDownTime(0);
					// 取得網絡鏈接狀態
					pApplication.setNetConnStatus(isWiFiActive(mcontext));
					// 判斷網絡鏈接狀態，若鏈接不成功則需要定時重新啟動同步服務。
					if (!pApplication.getNetConnStatus()) {
						pApplication.setDataSyncing(false);
						dt = new Date();
						DataSyncAlarm.setDataSyncAlarm(mcontext, true, dt
								.getTime() + 5 * 60 * 1000);
						return;
					}
					// 判斷死否進行影片同步
					if (lcount % pApplication.getVideoUpdInterValTime() == 1) {
						SysnVideoData();
						SystemClock.sleep(500);
					}
					// 判斷是否進行文章同步
					if (lcount % pApplication.getHandoutUpdInterValTime() == 1) {

						SysnHandoutData();
						SystemClock.sleep(500);
					}
					// 判斷是否進行公告同步
					if (lcount % pApplication.getVideoUpdInterValTime() == 1) {
						SysnNewsData();
						SystemClock.sleep(500);
					}

					// 判斷是否進行問卷調查同步
					if (lcount % pApplication.getSurveyUpdInterValTime() == 1) {
						SysnSurveyData();
						SystemClock.sleep(500);
					}
					// 返回已做問卷試題答案
					if (lcount % pApplication.getSurveyUpdInterValTime() == 1) {
						ReplySurveyData();
						SystemClock.sleep(500);
					}
					pApplication.setDataSyncing(false);
					// 判斷是否進行文件下載
					if (lcount % 3 == 1) {
						DownLoadFile();
						SystemClock.sleep(1000 * 2);
					}
					// 判斷是否進行未完成的文件下載。
					if (lcount % 3 == 2) {
						DownNotFinishedFile();
						SystemClock.sleep(1000 * 2);
					}
					// 判斷文件下載是否已經完成，若完成則需要設置下次進行同步的時間
					if (dHelper.getDowningCount() == 0) {
						pApplication.setDownloadFlag(false);
					}
					pApplication.setDataSyncing(false);
				} catch (Exception ex) {
					pApplication.setDataSyncing(false);
					pApplication.setDownloadFlag(false);
				}
			}
		}).start();
	}

	/**
	 * 訊息同步線程
	 */
	private void DownNotFinishedFileThread() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					DownNotFinishedFile();
				} catch (Exception ex) {
					return;
				}
			}
		}).start();
	}

	/**
	 * isWiFiActive：取得網絡鏈接狀態
	 * 
	 * @param inContext
	 */
	private static boolean isWiFiActive(Context inContext) {
		try {
			Context context = inContext.getApplicationContext();
			ConnectivityManager connectivity = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				NetworkInfo[] info = connectivity.getAllNetworkInfo();
				if (info != null) {
					for (int i = 0; i < info.length; i++) {
						if (info[i].getTypeName().equals("WIFI")
								&& info[i].isConnected()) {
							return true;
						}
					}
				}
			}
			return false;
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}

	}

	/**
	 * SysnVideoData：進行影片同步
	 */
	private void SysnVideoData() {

		InputStream inputStream = null;
		// Toast.makeText(mcontext, "同步影片", 1).show();
		String urlStr = String.format(VideoUrlFormat, pApplication.getWebUrl(),
				pApplication.getMainProveCode(), pApplication.getObjFrom(),
				pApplication.getObjID());
		// urlStr = "http://222.196.236.62/xml/video.xml";
		dHelper.setLpDateTime();
		try {
			// 取得服務器上影片的Stream數據
			URL url = new URL(urlStr);
			inputStream = url.openStream();
		} catch (Exception ex) {
			// Toast.makeText(mcontext, "取得影片信息失敗", 1).show();
			return;
		}

		try {
			// 通過sax解析Stream取得xml影片列表
			List<pVideo> videosList = SaxReadXml.readVideo(inputStream);
			int iLen = videosList.size();
			long[] Ids = new long[iLen];
			pVideo video;
			for (int i = 0; i < iLen; i++) {
				video = videosList.get(i);
				Ids[i] = video.getID();
				// 判斷該影片是否已經存在且沒有更新
				if (dHelper.isExistsVideoByIDandTime(video.getID(), video
						.getLstUpdTime())) {
					continue;
				}
				// 判斷該影片是否存在但有更新
				if (dHelper.isExistsVideoByID(video.getID())) {
					dHelper.deleteVideoByID(video.getID());
				}
				// 添加影片
				dHelper.addVideo(video);
			}
			// 刪除在影片列表沒有的本地影片數據
			if (iLen > 0) {
				dHelper.deleteVideoNotIDS(Ids);
			}
		} catch (Exception ex) {
			// Toast.makeText(mcontext, "同步影片失敗", 1).show();
			return;
		}
	}

	/**
	 * SysnHandoutData：進行文章同步
	 */
	private void SysnHandoutData() throws InterruptedException {
		InputStream inputStream = null;

		String urlStr = String.format(HandoutUrlFormat, pApplication
				.getWebUrl(), pApplication.getMainProveCode(), pApplication
				.getObjFrom(), pApplication.getObjID());
		// urlStr = "http://222.196.236.62/xml/handout.xml";
		dHelper.setLpDateTime();
		int iLen = 0;
		try {
			// 取得服務器上文章的Stream數據
			URL url = new URL(urlStr);
			inputStream = url.openStream();
		} catch (Exception ex) {
			// Toast.makeText(mcontext, "取得文章數據失敗", 1).show();
			return;
		}

		try {
			List<Handout> handoutList = SaxReadXml.readHandout(inputStream);
			Handout handout;
			// 通過sax解析Stream取得xml文章列表
			iLen = handoutList.size();
			long[] Ids = new long[iLen];
			for (int i = 0; i < iLen; i++) {
				handout = handoutList.get(i);
				Ids[i] = handout.getID();
				// 判斷該文章是否已經存在且沒有更新
				if (dHelper.isExistsHandoutByIDandTime(handout.getID(), handout
						.getLstUpdTime())) {
					continue;
				}
				// 判斷該文章是否存在但有更新
				if (dHelper.isExistsHandoutByID(handout.getID())) {
					dHelper.deleteHandoutByID(handout.getID());
				}

				// 判斷是否存在小測驗
				if (handout.getQuestionnaire() != -1) {
					urlStr = String.format(QuestionUrlFormat, pApplication
							.getWebUrl(), pApplication.getMainProveCode(),
							pApplication.getObjFrom(), pApplication.getObjID(),
							handout.getQuestionnaire());
					// urlStr = "http://222.196.236.62/xml/question3.xml";
					try {
						// 取得小測驗Stream
						URL url = new URL(urlStr);
						inputStream = url.openStream();
					} catch (Exception ex) {
						// Toast.makeText(mcontext, "取得文章小測驗數據失敗", 1).show();
						continue;
					}

					try {
						// 通過sax解析Stream取得xml測驗列表
						List<Question> questionList = SaxReadXml
								.readQuestion(inputStream);
						int iqLen = questionList.size();
						Question question;
						for (int j = 0; j < iqLen; j++) {
							question = questionList.get(j);
							// 添加小測驗
							question.setQuestionnaireID(handout
									.getQuestionnaire());
							dHelper.addQuestion(question);
						}
					} catch (Exception ex) {
						// Toast.makeText(mcontext, "同步小測驗數據失敗", 1).show();
						continue;
					}
				}
				// 添加文章
				dHelper.addHandout(handout);
			}
			if (iLen > 0) {
				dHelper.deleteHandoutNotIDS(Ids);
			}
		} catch (Exception ex) {
			// Toast.makeText(mcontext, "同步文章數據失敗", 1).show();
			return;
		}

	}

	/**
	 *SysnSurveyData： 進行問卷同步
	 */
	private void SysnSurveyData() {
		InputStream inputStream = null;
		// Toast.makeText(mcontext, "同步问卷", 1).show();
		String urlStr = String.format(SurveyUrlFormat,
				pApplication.getWebUrl(), pApplication.getMainProveCode(),
				pApplication.getObjFrom(), pApplication.getObjID());
		// urlStr = "http://222.196.236.62/xml/survey.xml";
		dHelper.setLpDateTime();
		try {
			// 取得服務器上問卷的Stream數據
			URL url = new URL(urlStr);
			inputStream = url.openStream();
		} catch (IOException ex) {
			// Toast.makeText(mcontext, "取得問卷數據失敗", 1).show();
			return;
		}

		try {
			// 通過sax解析Stream取得xml問卷列表
			List<Survey> surveyList = SaxReadXml.readSurvey(inputStream);
			int iLen = surveyList.size();
			long[] Ids = new long[iLen];
			Survey survey;
			for (int i = 0; i < iLen; i++) {
				survey = surveyList.get(i);
				Ids[i] = survey.getID();
				// 判斷該問卷是否已經存在且沒有更新
				if (dHelper.isExistsSurveyByIDandTime(survey.getID(), survey
						.getLstUpdTime())) {
					continue;
				}
				// 判斷該問卷存在但有更新
				if (dHelper.isExistsSurveyByID(survey.getID())) {
					dHelper.deleteSurveyByID(survey.getID());
				}

				// 判斷問卷調查試題
				if (survey.getQuestionnaire() != -1) {
					urlStr = String.format(QuestionUrlFormat, pApplication
							.getWebUrl(), pApplication.getMainProveCode(),
							pApplication.getObjFrom(), pApplication.getObjID(),
							survey.getQuestionnaire());
					// urlStr = "http://222.196.236.62/xml/question1.xml";
					try {
						// 取得服務器上問卷試題的Stream數據
						URL url = new URL(urlStr);
						inputStream = url.openStream();
					} catch (IOException ex) {
						// Toast.makeText(mcontext, "取得問卷試題失敗", 1).show();
						continue;
					}

					try {
						// 通過sax解析Stream取得xml問卷試題列表
						List<Question> questionList = SaxReadXml
								.readQuestion(inputStream);
						int iqLen = questionList.size();
						Question question;
						for (int j = 0; j < iqLen; j++) {
							question = questionList.get(j);
							question.setQuestionnaireID(survey
									.getQuestionnaire());
							// 添加問卷試題
							dHelper.addQuestion(question);
						}
					} catch (Exception ex) {
						// Toast.makeText(mcontext, "同步問卷試題失敗", 1).show();
						continue;
					}
				}
				// 添加問卷
				dHelper.addSurvey(survey);
			}
			if (iLen > 0) {
				dHelper.deleteSurveyNotIDS(Ids);
			}
		} catch (Exception ex) {
			// Toast.makeText(mcontext, "同步問卷調查失敗", 1).show();
			return;
		}
	}

	/**
	 * SysnNewsData：進行公告同步
	 */
	private void SysnNewsData() {
		InputStream inputStream = null;
		// Toast.makeText(mcontext, "同步公告", 1).show();
		String urlStr = String.format(NewsUrlFormat, pApplication.getWebUrl());
		// urlStr = "http://222.196.236.62/xml/news.xml";
		dHelper.setLpDateTime();
		try {
			// 取得服務器上公告的Stream數據
			URL url = new URL(urlStr);
			inputStream = url.openStream();
		} catch (IOException ex) {
			// Toast.makeText(mcontext, "取得公告數據失敗", 1).show();
			return;
		}
		try {
			// 通過sax解析Stream取得xml公告列表
			List<pNews> newsList = SaxReadXml.readNews(inputStream);
			int iLen = newsList.size();
			pNews pnews;
			for (int i = 0; i < iLen; i++) {
				pnews = newsList.get(i);
				// 判斷該公告是否已經存在，若不存在則添加
				if (!dHelper.isExistsNewsByID(pnews.getID())) {
					dHelper.addNews(pnews);
				}
			}
		} catch (Exception ex) {
			// Toast.makeText(mcontext, "同步公告數據失敗", 1).show();
			return;
		}
	}

	/**
	 *ReplySurveyData： 問卷調查反饋
	 * 
	 * @throws UnsupportedEncodingException
	 */
	private void ReplySurveyData() throws UnsupportedEncodingException {
		// 取得需要返回的問卷調查反饋列表
		List<SurveyResult> sResults = dHelper.getNeedSendSurveyResult();
		int iLen = sResults.size();
		SurveyResult result;
		String strResult = "";
		String uriAPI = String.format(SurveyReplyUrlFormat, pApplication
				.getWebUrl(), pApplication.getMainProveCode(), pApplication
				.getObjFrom(), pApplication.getObjID());
		for (int i = 0; i < iLen; i++) {
			// 取得一條數據
			result = sResults.get(i);
			// 設定以post方式反饋結果。
			HttpPost httpRequest = new HttpPost(uriAPI);
			// 設置反饋參數
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("Reply_Xml",
					outputSurveyReplyXML(result)));
			try {
				// 發送反饋請求
				httpRequest.setEntity(new UrlEncodedFormEntity(params,
						HTTP.UTF_8));
				HttpResponse httpResponse = new DefaultHttpClient()
						.execute(httpRequest);
				// 若成功則更新結果，將該條反饋標誌置為1
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					strResult = EntityUtils.toString(httpResponse.getEntity());
					if (strResult.equals("Y")) {
						dHelper.updateSurveyResultFlag(result.getID(), 1);
					} else {
						strResult = "Error Response：" + strResult;
					}
				} else {
					strResult = "Error Response："
							+ httpResponse.getStatusLine().toString();
				}
			} catch (ClientProtocolException e) {
				strResult = e.getMessage().toString();
				return;
			} catch (UnsupportedEncodingException e) {
				strResult = e.getMessage().toString();
				return;
			} catch (IOException e) {
				strResult = e.getMessage().toString();
				return;
			}
		}
	}

	/**
	 * outputSurveyReplyXML：根據格式取得問卷調查反饋的xml字符流數據
	 * 
	 * @param _result
	 *            ：問卷調查試題答案
	 * @return String：規定xml格式的字符串
	 */
	private String outputSurveyReplyXML(SurveyResult _result) {
		try {
			// 設置時間格式字符串
			SimpleDateFormat sfd = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
			// 創建xml格式串
			XmlSerializer serializer = Xml.newSerializer();
			StringWriter writer = new StringWriter();
			serializer.setOutput(writer);
			// 按照格式進行xml文件組裝
			// <?xml version=鈥?.0鈥?encoding=鈥漊TF-8鈥?standalone=鈥漼es鈥?>
			serializer.startDocument("UTF-8", true);

			// <Data>
			serializer.startTag("", "Data");

			// <Questionnaire_ID>1</Questionnaire_ID>
			serializer.startTag("", "Questionnaire_ID");
			serializer.text(String.valueOf(_result.getQuestionNaire()));
			serializer.endTag("", "Questionnaire_ID");

			// <Replyer_Info>
			serializer.startTag("", "Replyer_Info");
			// <Replier><![CDATA[閫欐槸濮撳悕, 鏈€澶?0鍊嬩腑鏂囧瓧]]></Replier>
			serializer.startTag("", "Replier");
			serializer.cdsect(_result.getDoctorName());
			serializer.endTag("", "Replier");
			// /<Replier_Org><![CDATA[閫欐槸閱櫌, 鏈€澶?0鍊嬩腑鏂囧瓧]]></Replier_Org>
			serializer.startTag("", "Replier_Org");
			serializer.cdsect(_result.getOwnedHospitals());
			serializer.endTag("", "Replier_Org");
			// <Replier_Dept><![CDATA[閫欐槸绉戝垾, 鏈€澶?0鍊嬩腑鏂囧瓧]]></Replier_Dept>
			serializer.startTag("", "Replier_Dept");
			serializer.cdsect(_result.getDivisions());
			serializer.endTag("", "Replier_Dept");
			// <Reply_Time>2011/11/16 17:07:11</Reply_Time>
			serializer.startTag("", "Reply_Time");
			serializer
					.text(sfd.format(new Date(_result.getSurveyResultTime())));
			serializer.endTag("", "Reply_Time");
			serializer.endTag("", "Replyer_Info");

			// <QuestionList>
			serializer.startTag("", "QuestionList");
			String[] questionList = PublicFunc.split(_result
					.getSurveyResultCont(), "|*|");
			int iLen = questionList.length;
			String[] question;
			for (int i = 0; i < iLen; i++) {

				question = PublicFunc.split(questionList[i], "::");
				// <Question>
				serializer.startTag("", "Question");
				// <Question_ID>1</Question_ID>
				serializer.startTag("", "Question_ID");
				serializer.text(question[0]);
				serializer.endTag("", "Question_ID");
				// <Answer_Type>YesNo</Answer_Type>
				serializer.startTag("", "Answer_Type");
				serializer.text(question[1]);
				serializer.endTag("", "Answer_Type");

				// <AnswerList>
				serializer.startTag("", "AnswerList");
				// <Answer>1</Answer>
				serializer.startTag("", "Answer");
				serializer.text(question[2]);
				serializer.endTag("", "Answer");
				// </AnswerList>
				serializer.endTag("", "AnswerList");
				// </Question>
				serializer.endTag("", "Question");
			}
			// </QuestionList>
			serializer.endTag("", "QuestionList");
			// </Data>
			serializer.endTag("", "Data");
			serializer.endDocument();
			return writer.toString();
		} catch (Exception ex) {
			return "";
		}
	}

	/**
	 * DownNotFinishedFile：判斷是否存在為下載完成的文件
	 */
	private void DownNotFinishedFile() {
		// 取得正在下載的文件列表
		DownCount = 0;
		DownedCount = 0;
		DownErrorCount = 0;
		TryCount++;
		pApplication.setDownloadFlag(true);
		List<DowningFileInfo> dfInfos = dHelper.getNotFinishedDownFile();
		int iLen = 0;
		iLen = dfInfos.size();
		Date dt = new Date();
		pApplication.setLastDownTime(dt.getTime());
		DowningFileInfo dfInfo = null;
		for (int i = 0; i < iLen; i++) {
			// 循環取得每個文件
			dfInfo = dfInfos.get(i);
			// 判斷當前下載數量是否大於3，若大於3則等待
			while (dHelper.getDowningCount() > 1) {
				SystemClock.sleep(500);
			}
			// 判斷當前下該文件是否需要下載
			if (!dHelper.IsDowningByUrl(dfInfo.getUrl())
					&& !dHelper.IsDownedByUrl(dfInfo.getUrl())) {
				download(dfInfo.getUrl(), new File(dfInfo.getLocalPath()),
						dfInfo.getType(), dfInfo.getID());
				SystemClock.sleep(1000);
			}
		}
	}

	/**
	 * DownLoadFile：文件下載
	 */
	private void DownLoadFile() {
		int iLen = 0;
		DownCount = 0;
		DownedCount = 0;
		DownErrorCount = 0;
		dHelper.clearDowning();
		dHelper.clearDownlog();
		String url = "";
		pApplication.setDownloadFlag(true);
		// 取得需要下載的文章列表
		// Toast.makeText(mcontext, "下载文章", 1).show();
		List<Handout> handoutList = dHelper.getNeedDownPicHandoutList();
		Handout handout = null;
		iLen = handoutList.size();
		int jLen = 0;
		for (int i = 0; i < iLen; i++) {
			handout = handoutList.get(i);
			// 取得本地文章保存路徑
			dir = new File(pApplication.getPfizerDir() + "Handout/"
					+ handout.getID() + "/");
			// 取得網絡上圖標的URL
			url = String
					.format("%s%s", handout.getUrlPath(), handout.getIcon());
			// 判斷當前圖標是否正在下載
			if (!dHelper.IsDownedByUrl(url)) {
				// 下載圖標
				while (dHelper.getDowningCount() > 3) {
					SystemClock.sleep(500);
				}
				download(url, dir, 1, handout.getID());
				SystemClock.sleep(1000);
			}

			// 取得當前文章的內容頁面數量
			jLen = handout.getPicCnt();
			for (int j = 1; j <= jLen; j++) {
				// 取得內容頁面的網絡路徑
				url = String.format("%s%d-%d.%s", handout.getUrlPath(), handout
						.getID(), j, handout.getFilenameExtension());

				// 判斷當前內容頁面是否正在下載
				if (!dHelper.IsDownedByUrl(url)) {
					// 判斷當前下載數量是否大於3，若大於3則等待
					while (dHelper.getDowningCount() > 3) {
						SystemClock.sleep(500);
					}
					download(url, dir, 1, handout.getID());
					SystemClock.sleep(1000);
				}
			}
		}

		// Toast.makeText(mcontext, "下载影片", 1).show();
		pVideo video = null;
		// 取得需要下載的影片圖標列表
		List<pVideo> videosList = dHelper.getNeedDownPicVideoList();
		iLen = videosList.size();
		Date dt = new Date();
		// 設置當前下載時間
		pApplication.setLastDownTime(dt.getTime());
		dir = new File(pApplication.getPfizerDir() + "Video/Pic/");
		for (int i = 0; i < iLen; i++) {
			video = videosList.get(i);
			// 判斷當前圖標是否正在下載
			url = video.getPic();
			if (!dHelper.IsDownedByUrl(url)) {
				// 判斷當前下載數量是否大於3，若大於3則等待
				while (dHelper.getDowningCount() > 3) {
					SystemClock.sleep(500);
				}
				download(url, dir, 2, video.getID());
				SystemClock.sleep(1000);
			}
		}

		// 取得需要下載的影片列表
		videosList = dHelper.getNeedDownFileVideoList();
		iLen = videosList.size();
		dir = new File(pApplication.getPfizerDir() + "Video/Movies/");
		for (int i = 0; i < iLen; i++) {
			video = videosList.get(i);
			url = video.getNetFile();
			// 判斷當前圖標是否正在下載
			if (!dHelper.IsDownedByUrl(url)) {
				// 判斷當前下載數量是否大於3，若大於3則等待
				while (dHelper.getDowningCount() > 1) {
					SystemClock.sleep(500);
				}
				download(url, dir, 3, video.getID());
				SystemClock.sleep(1000);
			}
		}
	}

	private void download(final String path, final File dir,
			final int downType, final long parentID) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					int iThreadNum = 2;
					if (downType == 3) {
						iThreadNum = 3;
					}
					dHelper.setLpDateTime();
					DownCount++;
					FileDownloader loader = new FileDownloader(dHelper, path,
							dir, downType, parentID, iThreadNum);
					Log.e("DownLoad", path);
					loader.download(new DownloadProgressListener() {

						@Override
						public void onDownloadSize(int fileSize, int downSize) {

							Message msg = new Message();
							msg.what = 1;
							if (fileSize == downSize) {
								msg.what = 2;
								// dHelper.deleteDowningByUrl(path);
							}
							msg.getData().putInt("downSize", downSize);
							msg.getData().putInt("fileSize", fileSize);
							handler.sendMessage(msg);
						}
					});
				} catch (Exception e) {
					Message msg = new Message();
					msg.what = -1;
					if (e.getMessage().equals("1")) {
						dHelper.delDownlogByPath(path);
						msg.what = -2;
					}
					dHelper.deleteDowningByUrl(path);
					msg.getData().putString("error", e.getMessage());
					handler.sendMessage(msg);
					return;
				}
			}
		}).start();

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}
}
